package org.will.aop.t2;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.will.aop.TransactionManager;
import org.will.aop.UserService;

@Slf4j
public class UserServiceWrapper implements UserService {

    private UserService target;

    @Autowired
    private TransactionManager txManager;

    public UserServiceWrapper(UserService target, TransactionManager txManager) {
        this.target = target;
        this.txManager = txManager;
    }

    @Override
    public void save() {
        try{
            txManager.begin();
            target.save();
            txManager.commit();
        }catch (Exception e){
            txManager.rollback();
            log.error("保存用户发生异常", e);
        }
    }

    @Override
    public void update() {
        try{
            txManager.begin();
            target.update();
            txManager.commit();
        }catch (Exception e){
            txManager.rollback();
            log.error("保存用户发生异常", e);
        }
    }

    public static void main(String args[]){
        UserService userService = new UserServiceWrapper(new UserServiceT2Impl(), new TransactionManager());
        userService.update();
    }
}
